package com.yowasa.xiuxian.util;

import com.yowasa.xiuxian.exception.HandlerException;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StrUtil {

    private static Pattern pattern = Pattern.compile("\\$\\{\\w+\\}");

    public static String processTemplate(String template, Map<String, Object> params) {
        StringBuffer sb = new StringBuffer();
        Matcher m = pattern.matcher(template);
        while (m.find()) {
            String param = m.group();
            Object value = params.get(param.substring(2, param.length() - 1));
            m.appendReplacement(sb, value == null ? "" : value.toString());
        }
        m.appendTail(sb);
        return sb.toString();
    }

    public static String processTemplate(String template, Object obj) {
        String jStr = JSONUtils.toJson(obj);
        Map map = JSONUtils.toObject(jStr, Map.class);
        return processTemplate(template, map);
    }

    public static int checkAndConvert2Int(String value,String errorMsg) {
        if (!NumberUtils.isDigits(value)) {
            throw new HandlerException("未识别的"+errorMsg+":"+value);
        }
        int num = Integer.parseInt(value);
        if (num < 1) {
            throw new HandlerException("未识别的"+errorMsg+":"+value);
        }
        return num;
    }

}
